<template>
	<view class="clock-container">
		<!-- 项目名称 -->
		<view class="project-name">
			<text>{{ projectName }}</text>
		</view>

		<!-- 待办名称 -->
		<view class="task-name">
			<text>{{ todoName }}</text>
		</view>

		<!-- 倒计时和进度条 -->
		<view class="timer-section">
			<view class="progress-box">
				<canvas canvas-id="progressCanvas" class="progress-canvas"></canvas>
			</view>
			<uni-countdown class="countdown"
				:day="0"
				:hour="0"
				:minute="remainingMinutes"
				:second="remainingSeconds"
				:showDay="false"
				:showHour="false"
				:showColon="true"
				color="#333333"
				:fontSize=42
				:start="isClocking"
				@timeup="onTimeUp"
			/>
		</view>

		<!-- 简单专注 -->
		<button v-if="!isClocking"
			class="control-btn"
			:class="{ 'resting': isResting }"
			@click="toggleTimer"
		>
			简单专注
		</button>

		<!-- 项目专注 -->
		<button
			class="control-btn"
			:class="{ 'resting': isResting }"
			@click="toggleProjectTimer"
		>
			{{ buttonText }}
		</button>

		<!-- 说明文字 -->
		<view class="focus-desc-text">
			<text>项目专注: 属于某个项目的某个待办, 需创建项目和待办.</text>
			<text>简单专注: 独立番茄钟计时, 不属于任何项目.</text>
		</view>
	</view>
</template>

<script setup>
import { ref, computed, onMounted, nextTick } from 'vue'
import { onShow } from '@dcloudio/uni-app';
import request from '../../utils/request';
import { useTodoStore } from '../../stores/todo';

const WORKING_MINUTES = 30;
const RESTING_MINUTES = 5;
const DEFAULT_PROJECT_NAME = '番茄跃动';
const DEFAULT_TODO_NAME = '助你专注';

// 状态变量
const todoStore = useTodoStore();
const isClocking = ref(false);
const isResting = ref(false);
const remainingMinutes = ref(WORKING_MINUTES); // 默认专注时长30分钟
const remainingSeconds = ref(0);
const progress = ref(0);
let timer = null;
let screenWidth = 0;

// 项目和任务名称
const projectName = ref(DEFAULT_PROJECT_NAME);
const todoName = ref(DEFAULT_TODO_NAME);

let projectId = null;
let todoId = null;

const rpxToPx = (rpx) => {
	return (rpx / 750) * screenWidth;
}

// 绘制环形进度条
const drawProgress = (progress) => {
	// console.log('drawProgress_. progress:', progress);
	const ctx = uni.createCanvasContext('progressCanvas', this);

	// const centerX = rpxToPx(150); // 圆心 X 坐标
	// const centerY = rpxToPx(150); // 圆心 Y 坐标
	// const radius = rpxToPx(140); // 圆的半径
	// // console.log('drawProgress_. centerX:', centerX, 'centerY:', centerY, 'radius:', radius);
	// const startAngle = -Math.PI / 2; // 起始角度（从顶部开始）
	// const endAngle = startAngle + (-2 * Math.PI * progress) / 100; // 结束角度

	// 获取canvas的实际尺寸
	const query = uni.createSelectorQuery();
	query.select('.progress-canvas').boundingClientRect(data => {
		const canvasWidth = data.width;
		const canvasHeight = data.height;
		
		// 使用canvas实际尺寸的一半作为中心点和半径
		const centerX = canvasWidth / 2;
		const centerY = canvasHeight / 2;
		const radius = Math.min(canvasWidth, canvasHeight) / 2 - 10; // 留出10px边距
		
		const startAngle = -Math.PI / 2; // 起始角度（从顶部开始）
		const endAngle = startAngle + (-2 * Math.PI * progress) / 100; // 结束角度
		
		// 绘制背景圆环
		ctx.beginPath();
		ctx.setLineWidth(10);
		ctx.setStrokeStyle('#007aff');
		ctx.arc(centerX, centerY, radius, 0, 2 * Math.PI);
		ctx.stroke();

		// 绘制进度圆环
		ctx.beginPath();
		ctx.setLineWidth(10);
		ctx.setStrokeStyle('#e6e6e6');
		ctx.arc(centerX, centerY, radius, startAngle, endAngle);
		ctx.stroke();

		ctx.draw();
	}).exec();	
}

onShow(async () => {
	const params = uni.getStorageSync('startClockParams') || {};
	console.log('clock_ onShow_. params:', params);
	projectId = params.projectId;
	todoId = params.todoId;
	const startClock = params.startClock;
	if (startClock) {
		isClocking.value = true;
		startTimer({isProjectFocus: true});
		uni.setStorageSync('startClockParams', { ...params, startClock: false });
	}

	if (projectId) {
		try {
			const res = await request({
				url: '/app/project/project/info',
				method: 'GET',
				data: { id: projectId }
			});
			console.log('clock_ onShow_. projectName:', res.data?.name);
			if (res.data?.name) {
				projectName.value = `项目: ${res.data.name}`;
			}
		} catch (e) {
			console.log('获取项目失败:', e);
		}
	}

	if (todoId) {
		try {
			const res = await request({
				url: '/app/todo/todo/info',
				method: 'GET',
				data: { id: todoId }
			});
			console.log('clock_ onShow_. todoName:', res.data?.name);
			if (res.data?.name) {
				todoName.value = `待办: ${res.data.name}`;
			}
		} catch (e) {
			console.log('获取待办失败:', e);
		}
	}
});

onMounted(() => {
	screenWidth = uni.getSystemInfoSync().windowWidth;
	drawProgress(progress.value);
})

// 计算属性
const buttonText = computed(() => {
	if (!isClocking.value) return '项目专注'
	if (isResting.value) return '放弃休息'
	return '放弃专注'
})

// 项目专注
const toggleProjectTimer = () => {
	if (!isClocking.value) {
		console.log('toggleProjectTimer_. not working, start timer.');
		startTimer({isProjectFocus: true});
	} else {
		console.log('toggleProjectTimer_. is working, stop timer.');
		stopTimer();
	}
}


// 开始/停止专注方法
const toggleTimer = () => {
	if (!isClocking.value) {
		console.log('toggleTimer_. not working, start timer.');
		startTimer({isProjectFocus: false});
	} else {
		console.log('toggleTimer_. is working, stop timer.');
		stopTimer();
	}
}

// isProjectFocus: 是否是项目专注(即从项目点击番茄图标启动专注)
const startTimer = ({isProjectFocus = false}) => {
	console.log('startTimer_. isProjectFocus:', isProjectFocus);
	if (isProjectFocus && !todoId) {
		uni.showModal({
			title: '提示',
			content: '请先在项目页面中创建待办, 点击待办右侧的番茄图标来启动专注. 是否跳转到项目页面?',
			confirmText: '去项目',
			cancelText: '取消',
			success: (res) => {
				if (res.confirm) {
					uni.switchTab({
						url: '/pages/project/index'
					});
				}
			}
		});
		return;
	}
	if (!isProjectFocus) {
		// 简单专注, 清除项目和待办相关信息
		projectId = null;
		todoId = null;
		projectName.value = DEFAULT_PROJECT_NAME;
		todoName.value = DEFAULT_TODO_NAME;
		// 清除 StorageSync 的 startClockParams
		uni.removeStorageSync('startClockParams');
	}

	isClocking.value = true;
	// 开始倒计时
	const totalSeconds = isResting.value ? RESTING_MINUTES * 60 : WORKING_MINUTES * 60; // 休息5分钟, 专注30分钟
	let currentSeconds = totalSeconds;

	timer = setInterval(() => {
		currentSeconds--;
		// remainingMinutes.value = Math.floor(currentSeconds / 60);
		// remainingSeconds.value = currentSeconds % 60;
		progress.value = (currentSeconds / totalSeconds) * 100;
		drawProgress(progress.value);

		if (currentSeconds <= 0) {
			clearInterval(timer);
			onTimeUp();
		}
	}, 1000);
}

const stopTimer = () => {
	if (timer) {
		clearInterval(timer)
		timer = null
	}
	isClocking.value = false;
	isResting.value = false;
	remainingMinutes.value = WORKING_MINUTES;
	remainingSeconds.value = 0;
	progress.value = 0;
	drawProgress(progress.value);

	// 强制更新 uni-countdown 组件
	nextTick(() => {
		isClocking.value = true; // 先设置为 true 触发一次更新
		nextTick(() => {
			isClocking.value = false; // 再设置为 false 完成重置
		});
	});

}

const onTimeUp = () => {
	console.log('onTimeUp_. isResting:', isResting.value);
	if (!isResting.value) {
		// 专注时间结束，开始休息
		isResting.value = true
		remainingMinutes.value = 5
		remainingSeconds.value = 0
		progress.value = 0
		// 将本次专注时间记录到后端
		if (projectId && todoId) {
			console.log("onTimeUp. report time.");
			todoStore.addTime(projectId, todoId, WORKING_MINUTES);
		}

		startTimer({isProjectFocus: !!todoId});
	} else {
		// 休息时间结束，重置状态
		stopTimer();
	}
}

</script>

<style>
.clock-container {
	flex: 1;
	display: flex;
	flex-direction: column;
	align-items: center;
	padding: 40rpx;
}

.project-name {
	font-size: 36rpx;
	font-weight: bold;
	margin-bottom: 20rpx;
}

.task-name {
	font-size: 32rpx;
	margin-bottom: 40rpx;
}

.timer-section {
	position: relative;
	width: 300rpx;
	height: 300rpx;
	margin: 40rpx 0;

	display: flex;
	justify-content: center;
	align-items: center;
}

.progress-box {
	width: 300rpx;
	height: 300rpx;
}

.progress-canvas {
   width: 300rpx;
   height: 300rpx;
}

.countdown {
	position: absolute;
	top: 0;
	width: 100%;
	height: 100%;
	display: flex;
	justify-content: center;
	align-items: center;
}

.control-btn {
	width: 60%;
	height: 88rpx;
	line-height: 88rpx;
	text-align: center;
	background-color: #FF6B6B;
	color: #FFFFFF;
	border-radius: 44rpx;
	font-size: 32rpx;
	margin-top: 40rpx;
	/* background-color: #fff; */
}

.control-btn.resting {
	background-color: #4CAF50;
}

.focus-desc-text {
	font-size: 24rpx;
	color: #999999;
	margin-top: 20rpx;

	display: flex;
	flex-direction: column;
	align-items: center;
}

</style>